package xquery;

import java.util.ArrayList;

import org.w3c.dom.Node;

import xquery.XPathComposedExp.XPathOperator;

public class XQuerySimpleCond extends XQuery {
	enum XQueryOperator {
		IS, EQ, EMPTY, AND, OR, NOT;
		
		public static XQueryOperator string2op(String s) {
			if (s.equals("is"))
				return IS;
			else if (s.equals("eq"))
				return EQ;
			else
				return null;
		}
	}
	
	XQueryOperator op;
	XQExpression[] operand;
	
	@Override
	public XPathData eval(XQContext context, ArrayList<Node> currentNodeList) {
		XPathData result = operand[0].eval(context, currentNodeList);
		for(int i=1;i<operand.length;i++){
			switch(op){
			case IS:
				result = new XPathData(result.is(operand[i].eval(context, currentNodeList)));
				break;
			case EQ:
				result = new XPathData(result.eq(operand[i].eval(context, currentNodeList)));
				break;
			case AND:
				result = new XPathData(result.getBool() && (operand[i].eval(context, currentNodeList)).getBool());
				break;
			case OR:
				result = new XPathData(result.getBool() || (operand[i].eval(context, currentNodeList)).getBool());
				break;
			}
		}
		
		if(op == XQueryOperator.NOT)
			result = new XPathData(!result.getBool());
		else if (op == XQueryOperator.EMPTY)
		{
			boolean isEmpty = result.getList().isEmpty();
			result = new XPathData(isEmpty);
		}		
		return result;
	}
	public String toString()
	{
		StringBuffer sb = new StringBuffer("");
		String operator = "";
		switch(op)
		{
			case EQ:
				operator  = " eq ";
				break;
			case AND:
				operator = " and ";
				break;
		}
		sb.append(operand[0]);
		for(int i=1;i<operand.length;i++)
		{
			sb.append(operator);
			sb.append(operand[i]);
		}
		return sb.toString();
	}
}
